Page({
  data: {
    isLoggedIn: false,
    userInfo: {
      nickname: '',
      avatar: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
      desc: ''
    },
    userStats: {
      following: 0,
      followers: 0,
      likes: 0
    },
    // 登录状态
    showLoginForm: false,
    tempUserInfo: {
      nickname: '',
      avatar: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
    },
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
    // 设置弹窗状态
    showSettingsForm: false,
    tempSettingsInfo: {
      nickname: '',
      avatar: '',
      desc: ''
    },
    // 显示用的个性签名
    displayDesc: '这个人很懒，什么都没写...',
    // 个性签名字符长度
    descLength: 0
  },

  onLoad: function(options) {
    this.checkLoginStatus();
  },

  onShow: function() {
    this.checkLoginStatus();
    this.updateUserStats();
    
    // 检查是否需要更新统计数据
    const app = getApp();
    if (app.globalData && app.globalData.needUpdateStats) {
      this.updateUserStats();
      app.globalData.needUpdateStats = false;
    }
  },

  // 更新用户统计数据
  updateUserStats: function() {
    // 获取关注数量
    const followedAuthors = wx.getStorageSync('followedAuthors') || [];
    const followingCount = followedAuthors.length;
    
    // 获取发布文章数量
    const userPublishedArticles = wx.getStorageSync('userPublishedArticles') || [];
    const publishedCount = userPublishedArticles.length;
    
    // 更新统计数据
    this.setData({
      userStats: {
        following: followingCount,
        followers: 0, // 暂时设为0，可以后续扩展
        published: publishedCount
      }
    });
  },

  // 检查登录状态
  checkLoginStatus: function() {
    const app = getApp()
    if (app.globalData.isLoggedIn && app.globalData.userInfo) {
      this.setData({
        isLoggedIn: true,
        userInfo: app.globalData.userInfo
      });
      this.updateDisplayDesc(app.globalData.userInfo.desc);
    } else {
      // 检查本地存储
      const userInfo = wx.getStorageSync('userInfo');
      if (userInfo) {
        app.globalData.userInfo = userInfo
        app.globalData.isLoggedIn = true
        this.setData({
          isLoggedIn: true,
          userInfo: userInfo
        });
        this.updateDisplayDesc(userInfo.desc);
      }
    }
  },

  // 更新显示用的个性签名
  updateDisplayDesc: function(desc) {
    const fullDesc = desc || '这个人很懒，什么都没写...';
    const displayDesc = fullDesc.length > 10 ? fullDesc.substring(0, 10) + '...' : fullDesc;
    this.setData({
      displayDesc: displayDesc
    });
  },

  // 显示登录表单
  showLoginForm: function() {
    this.setData({
      showLoginForm: true,
      tempUserInfo: {
        nickname: '',
        avatar: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
      }
    })
  },

  // 取消登录
  cancelLogin: function() {
    this.setData({
      showLoginForm: false
    })
  },

  // 选择头像
  onChooseAvatar: function(e) {
    const { avatarUrl } = e.detail
    this.setData({
      'tempUserInfo.avatar': avatarUrl
    })
  },

  // 昵称输入
  onNicknameChange: function(e) {
    const nickname = e.detail.value
    this.setData({
      'tempUserInfo.nickname': nickname
    })
  },

  // 完成登录
  completeLogin: function() {
    const { nickname, avatar } = this.data.tempUserInfo
    const defaultAvatar = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
    
    if (!nickname.trim()) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none'
      })
      return
    }

    if (avatar === defaultAvatar) {
      wx.showToast({
        title: '请选择头像',
        icon: 'none'
      })
      return
    }

    const app = getApp()
    const userInfo = app.saveUserInfo({
      nickname: nickname.trim(),
      avatar: avatar
    })

    this.setData({
      isLoggedIn: true,
      userInfo: userInfo,
      showLoginForm: false
    })

    // 更新显示用的个性签名
    this.updateDisplayDesc(userInfo.desc);

    wx.showToast({
      title: '登录成功',
      icon: 'success'
    })
  },

  // 编辑个人资料
  editProfile: function() {
    if (!this.data.isLoggedIn) {
      this.showLoginForm();
      return;
    }
    
    const currentDesc = this.data.userInfo.desc === '这个人很懒，什么都没写...' ? '' : (this.data.userInfo.desc || '');
    
    // 先设置临时数据，再显示弹窗，避免闪烁
    this.setData({
      tempSettingsInfo: {
        nickname: this.data.userInfo.nickname,
        avatar: this.data.userInfo.avatar,
        desc: currentDesc
      },
      descLength: currentDesc.length
    }, () => {
      // 在数据设置完成后再显示弹窗
      this.setData({
        showSettingsForm: true
      });
    });
  },

  // 取消设置
  cancelSettings: function() {
    // 先隐藏弹窗，再重置数据，避免闪烁
    this.setData({
      showSettingsForm: false
    }, () => {
      // 重置临时数据
      this.setData({
        tempSettingsInfo: {
          nickname: '',
          avatar: '',
          desc: ''
        },
        descLength: 0
      });
    });
  },

  // 选择设置中的头像
  onChooseSettingsAvatar: function(e) {
    const { avatarUrl } = e.detail;
    this.setData({
      'tempSettingsInfo.avatar': avatarUrl
    });
  },

  // 设置中的昵称输入
  onSettingsNicknameChange: function(e) {
    const nickname = e.detail.value;
    this.setData({
      'tempSettingsInfo.nickname': nickname
    });
  },

  // 设置中的个性签名输入
  onSettingsDescChange: function(e) {
    const desc = e.detail.value || '';
    // 确保字符数不超过50
    const trimmedDesc = desc.length > 50 ? desc.substring(0, 50) : desc;
    this.setData({
      'tempSettingsInfo.desc': trimmedDesc,
      descLength: trimmedDesc.length
    });
  },

  // 完成设置修改
  completeSettings: function() {
    const { nickname, avatar, desc } = this.data.tempSettingsInfo;
    
    if (!nickname.trim()) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none'
      });
      return;
    }

    // 检查个性签名字数限制
    if (desc.trim().length > 50) {
      wx.showToast({
        title: '个性签名不能超过50个字',
        icon: 'none'
      });
      return;
    }

    const newUserInfo = {
      ...this.data.userInfo,
      nickname: nickname.trim(),
      avatar: avatar,
      desc: desc.trim() || '这个人很懒，什么都没写...'
    };

    // 更新本地存储
    wx.setStorageSync('userInfo', newUserInfo);
    getApp().globalData.userInfo = newUserInfo;

    // 先更新用户信息和隐藏弹窗
    this.setData({
      userInfo: newUserInfo,
      showSettingsForm: false
    }, () => {
      // 在弹窗隐藏后重置临时数据
      this.setData({
        tempSettingsInfo: {
          nickname: '',
          avatar: '',
          desc: ''
        },
        descLength: 0
      });
    });

    // 更新显示用的个性签名
    this.updateDisplayDesc(newUserInfo.desc);

    wx.showToast({
      title: '修改成功',
      icon: 'success'
    });
  },

  // 查看关注列表
  viewFollowing: function() {
    if (!this.data.isLoggedIn) {
      this.showLoginForm();
      return;
    }
    
    // 设置全局变量，告诉community页面需要切换到关注标签
    const app = getApp();
    app.globalData.switchToFollowTab = true;
    
    // 跳转到community页面
    wx.switchTab({
      url: '/pages/community/community'
    });
  },

  // 查看我的发布
  viewMyPublished: function() {
    if (!this.data.isLoggedIn) {
      this.showLoginForm();
      return;
    }
    
    wx.navigateTo({
      url: '/pages/my-published/my-published'
    });
  },

  // 查看收藏
  viewCollection: function() {
    if (!this.data.isLoggedIn) {
      this.showLoginForm();
      return;
    }
    
    wx.navigateTo({
      url: '/pages/collection/collection'
    });
  },

  // 查看学习记录
  viewHistory: function() {
    if (!this.data.isLoggedIn) {
      this.showLoginForm();
      return;
    }
    
    wx.navigateTo({
      url: '/pages/study-records/study-records'
    });
  },

  // 关于
  viewAbout: function() {
    wx.showModal({
      title: '关于我们',
      content: '英语学习社区是一个专注于英语学习的交流平台，提供单词学习、翻译练习、听力训练等多种功能，帮助用户提升英语水平。',
      showCancel: false
    });
  },

  // 退出登录
  logout: function() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          const app = getApp()
          app.logout()
          
          this.setData({
            isLoggedIn: false,
            userInfo: {
              nickname: '',
              avatar: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
              desc: ''
            }
          });
          
          wx.showToast({
            title: '已退出登录',
            icon: 'success'
          });
        }
      }
    });
  }
})